﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LeadExpress.Models;

namespace LeadExpress.Repository
{
    public class StateRepository
    {
        LeadExpressEntities entities = new LeadExpressEntities();

        public IQueryable<State> GetAll(bool active)
        {
            return from c in entities.States where (c.Active == active) orderby c.Name ascending select c;
        }

        public List<OptionModel> GetAllItems()
        {
            List<OptionModel> list = new List<OptionModel>();

            var items = (from c in entities.States
                         orderby c.Name ascending
                         select c);

            list.Add(new OptionModel { ID = "-1", Name = "All" });
            // Add items
            foreach (var item in items)
            {
                OptionModel model = new OptionModel();
                model.ID = item.ID.ToString();
                model.Name = item.Name;
                list.Add(model);
            }

            return list;
        }

        public List<Models.StateModel> GetAll()
        {
            List<Models.StateModel> list = new List<Models.StateModel>();
            var items = (from c in entities.States
                    orderby c.IsTop descending, c.Name ascending
                    select c);

            foreach (var item in items)
            {
                Models.StateModel model = new Models.StateModel();
                model.ID = item.ID;
                model.Name = item.Name;
                model.IsTop = item.IsTop;
                model.Ordered = Convert.ToInt32(item.SortOrder);
                model.DateCreated = Convert.ToDateTime(item.DateCreated).ToString("dd-MM-yyyy hh:mm tt");
                model.Active = item.Active;
                model.DeleteDialog = string.Format("DeleteDialog('{0}')", item.ID);
                list.Add(model);
            }

            return list;
        }

        public State GetSingle(string id)
        {
            return (from c in entities.States where c.ID == id select c).FirstOrDefault();
        }

        public void Create(State _object)
        {
            try
            {
                _object.DateCreated = System.DateTime.Now;
                entities.AddToStates(_object);
                entities.SaveChanges();
            }
            catch
            {
            }
        }

        public void Save(State _object)
        {
            entities.SaveChanges();
        }

        public void Delete(string id)
        {
            var _object = (from _list in entities.States where _list.ID == id select _list).First();
            entities.DeleteObject(_object);
            entities.SaveChanges();
        }
    }
}